package com.jiusit.redisMain.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.SortingParams;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jiusit.redisMain.interceptor.UserInterceptor;
import com.jiusit.redisMain.model.WxAccessToken;

@ControllerBind(controllerKey = "/test")
public class TestController extends Controller {
	private static final Logger log = Logger.getLogger(TestController.class);
	
	public void redis_get() {
		String key = getPara("key");
		String valueJedis , valueCache=null;
		Cache cache = Redis.use();
		Jedis jedis = cache.getJedis();
		valueJedis = jedis.get(key);
		log.debug("key " +key +" value is "+valueJedis+" by jedis");
		jedis.close();
		log.debug("key "+key+" exist: "+cache.exists(key));
		try{
			valueCache = cache.get(key);
			log.debug("key " +key +" value is "+valueCache+" by cache");
		}catch(Exception e) {
			e.printStackTrace();
			renderText("fail");
		}
		renderText("sucess\r\n"
				+ "key " +key +" value is "+valueJedis+" by jedis\r\n"
				+ "key " +key +" value is "+valueCache+" by cache");
	}
	
	public void redis_set() {
		String key = getPara("key");
		String value = getPara("value");
		int exn = getParaToInt("exn");
		
		Cache cache = Redis.use();
		try{
			cache.setex(key, exn, value);
		}catch(Exception e) {
			e.printStackTrace();
		}
		Jedis jedis = cache.getJedis();
		jedis.setex(key, exn, value);
		jedis.close();
		renderText("sucess");
	}
	
	public void index() {
		get();
	}
 
	/**
	 * 获取Token
	 */
	public void get() {
		String callback = getPara("jsoncallback");
		//String accessToken = Redis.use().get("ytv.accessToken");
		Jedis jedis = Redis.use().getJedis();
		String accessToken = jedis.get("ytv.accessToken");
		//检测是否有效   -- 无法检测
		if (StrKit.isBlank(accessToken)) {
			String userAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + PropKit.get("ytvAppId") + "&secret="
					+ PropKit.get("ytvSecret");
			String userAccessTokenData = HttpKit.get(userAccessTokenUrl);
			log.debug("accessToken is refush "+userAccessTokenData);
			if (StrKit.notBlank(userAccessTokenData)) {
				Map userAccessToken = JSON.parseObject(userAccessTokenData, HashMap.class);
				if (userAccessToken!=null && userAccessToken.get("errcode")!=null && Long.valueOf(userAccessToken.get("errcode").toString())==0) {
					accessToken = userAccessToken.get("access_token").toString();
					//Redis.use().setex("ytv.accessToken", 7000, accessToken);
					jedis.setex("ytv.accessToken", 7000, accessToken);
					try {
						WxAccessToken wxAccessToken = new WxAccessToken();
						wxAccessToken.set("access_token", accessToken);
						wxAccessToken.set("token_type", "user");
						wxAccessToken.set("create_time", new Date());
						wxAccessToken.set("expires_in", 7000);
						wxAccessToken.set("refresh_token", "");
						wxAccessToken.save();
					} catch (Exception e) {
						log.debug("save wxAccessToken is error " + e.getMessage());
					}
				}
			}
		} else {
			log.debug("UserAccessToken is use cache: "+accessToken);
		}
		jedis.close();
		if (StrKit.isBlank(callback)) {
			renderText(accessToken);
			return;
		} else {
			renderJson(callback + "(" + JsonKit.toJson(accessToken) + ")");
			return;
		}
	}
	public void testRedis(){
		Jedis jedis = Redis.use().getJedis();
		jedis.set("test1", "1");
		System.out.println(jedis.ping());
		/*jedis.lpush("ceshi", "ceshi1");
		jedis.lpush("ceshi", "ceshi2");
		jedis.lpush("ceshi", "ceshi3");
		jedis.lpush("ceshi", "ceshi4");
		jedis.lpush("ceshi", "ceshi5");*/
		//SortingParams sortPara=new SortingParams();
		//sortPara =sortPara.alpha();
		//System.out.println(jedis.sort("ceshi", sortPara));
		//jedis.incr("test1");
		//jedis.append("test1", "ceshi");
		//jedis.set("test2", "testRedis2");
		//jedis.mset("test1","testRedis2","test2","testRedis3");
		log.debug(jedis.get("test1"));
		renderJson(jedis.get("test1"));
	}
	//获取匹配某个字符串key对应的value
	public void getAllKey(){
		Map<String,String> map=new HashMap<String,String>();
		Jedis jedis = Redis.use().getJedis();
		Set<String> set=jedis.keys("test*");
		Iterator<String>iterator= set.iterator();
        while(iterator.hasNext()){
        	String key=iterator.next();
        	String value=jedis.get(key);
        	map.put(key, value);
        	System.out.println(key+"---------"+value);
        }
        renderJson(map);
	}
	
	//往list set和get
		public void lpush(){
			Map<String,String> map=new HashMap<String,String>();
			Jedis jedis = Redis.use().getJedis();
			jedis.lpush("lpush", "lpush1");
			jedis.lpush("lpush", "lpush2");
			jedis.lpush("lpush", "lpush3");
			jedis.lpush("lpush", "lpush4");
			jedis.lpush("lpush", "lpush5");
			//System.out.println(jedis.lrange("lpush", 0, -1));
			SortingParams sortPara=new SortingParams();
			sortPara =sortPara.alpha();
			System.out.println(jedis.sort("lpush",sortPara));
			//List<String> list=jedis.lrange("lpush", 0, -1);
			List<String> list=jedis.sort("lpush",sortPara); //排序
			for(String str:list){
				map.put(str, str);
				}
	        renderJson(map);
	        System.out.println(jedis.get("objStr"));
	        jedis.set("objStr",map.toString());
		}
		//返回随机数,不移除
				public void srandmember(){
					Map<String,String> map=new HashMap<String,String>();
					Jedis jedis = Redis.use().getJedis();
					jedis.sadd("srandmember", "srandmember1");
					jedis.sadd("srandmember", "srandmember2");
					jedis.sadd("srandmember", "srandmember3");
					jedis.sadd("srandmember", "srandmember4");
					jedis.sadd("srandmember", "srandmember5");
					String randStr=jedis.srandmember("srandmember");
					//String randStrSpop=jedis.spop("srandmember");
					System.out.println(randStr); 
					SortingParams sortPara=new SortingParams();
					sortPara =sortPara.alpha();
					System.out.println(jedis.sort("lpush",sortPara));
					//List<String> list=jedis.lrange("lpush", 0, -1);
					List<String> list=jedis.sort("lpush",sortPara); //排序
					for(String str:list){
						map.put(str, str);
						}
			        renderJson(map);
			        System.out.println(jedis.get("objStr"));
			        jedis.set("objStr",map.toString());
				}
				//返回随机数并从redis中移除
				public void spop(){
					Map<String,String> map=new HashMap<String,String>();
					Jedis jedis = Redis.use().getJedis();
					//jedis.sadd("spop", "spop1");
					//jedis.sadd("spop", "spop2");
					//jedis.sadd("spop", "spop3");
					//jedis.sadd("spop", "spop4");
					//jedis.sadd("spop", "spop5");
					//String randStr=jedis.srandmember("srandmember");
					String randStrSpop=jedis.spop("spop");
					System.out.println(randStrSpop);
					Set<String> set=jedis.smembers("spop");
					Iterator<String>iterator= set.iterator();
			        while(iterator.hasNext()){
			        	String key=iterator.next();
			        	//String value=jedis.get(key);
			        	map.put(key, key);
			        	System.out.println(key+"---------"+key);
			        }
			        renderJson(map);
				}
				
}
